package com.example.springboot.service.imp;


import com.example.springboot.dao.CityMapper;
import com.example.springboot.entity.City;
import com.example.springboot.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by tang on 2017/12/4.
 */
@Transactional
@Service
public class CityServiceImp implements CityService {

    @Autowired
    private CityMapper cityMapper;

    @Autowired

    private
    RedisTemplate redisTemplate;

    @Override
    public City findByCityName(String cityName) {
        //从缓存中获取城市信息
        String key = "city_" + cityName;
        ValueOperations<String, City> operations = redisTemplate.opsForValue();

        //缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            City city = operations.get(key);
            System.out.println("CityServiceImpl.findCityById(): 从缓存中获取了城市 -> " + city.toString());
            return city;
        }

        //从 DB 中获取城市信息
        City city = cityMapper.findByName(cityName);
        //插入缓存
        if(city!=null){
            operations.set(key, city, 10, TimeUnit.SECONDS);
            System.out.println("CityServiceImpl.findCityById(): 城市插入缓存 -> " + city.toString());
        }

        return city;
    }

    @Override
    public List<City> findAll() {
        return cityMapper.findAll();
    }

    @Override
    public void updateCity(City city) {
        cityMapper.updateCity(city);
        String key = "city_" + city.getCityName();
        boolean hasKey = redisTemplate.hasKey(key);

        if (hasKey) {
            redisTemplate.delete(key);
        }

    }

    @Override
    public void addCity(City city) {
        cityMapper.addCity(city);
    }
}
